package com.topisv.tms.web;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.OrdenoSource;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.entity.ShopSource;
import com.topisv.tms.entity.WarehouseArea;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomerAreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.ShopSourceService;
import com.topisv.tms.service.WarehouseAreaService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.utils.JsonUtil;
//import com.topisv.tms.utils.enums.StatusEnums;
//import com.topisv.tms.utils.http.SynchroShippedBatchQueue;
import com.topisv.tms.utils.rule.TMSTransportRule;
import com.topisv.tms.utils.vo.RestCustomersAreagroupVo;
import com.topisv.tms.vo.warehouse.WarehouseAreaParamVo;
import com.topisv.tms.web.base.BaseDataTableController;

import net.sf.json.JSONObject;

/**
 * 角色管理的Controller, 使用Restful风格的Urls:
 * 
 * List page : GET /customers/ Create page : GET /customers/create Create action
 * : POST /customers/create Update page : GET /customers/update/{id} Update
 * action : POST /customers/update Delete action : GET /customers/delete/{id}
 * 
 * @author Arthur
 */
@Controller
@RequestMapping(value = "v2/customers")
public class CustomersController extends BaseDataTableController{

    private static final Logger log = LoggerFactory.getLogger(CustomersController.class);
	

	@Autowired
	private CustomersService customersService;
	@Autowired
	private CustomerAreaGroupService customerAreaGroupService;
	@Autowired
	private ShopSourceService shopSourceService;
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private WarehouseAreaService warehouseAreaService;

	@RequestMapping(value = "v2_show")
	public String list() {
		return "customers/customersList";
	}
	
	@RequestMapping(value = "page")
	public void page(@RequestBody JSONParam[] paramJson, HttpServletRequest request,HttpServletResponse response){
		try {
			// 客户端参数
			QueryParamHolder paramHolder = collectParam(paramJson);
			Page<Customers> page = customersService.pageCustomers(paramHolder);
			// 封装查询结果
			response.getWriter().print(bulidJSON(page));
		} catch (Exception e) {
			
		}
	}
	
	@RequestMapping(value = "customerDetail")
	public void CustomerDetail(HttpServletRequest request,
			HttpServletResponse response) {
		String idString = request.getParameter("id");
		long id = Long.valueOf(idString);
		Customers customer = customersService.findOne(id);
		Map<String, Customers> map = new HashMap<String, Customers>();
		map.put("customer", customer);
		String json = JsonUtil.getObjectString(map);
		PrintWriter out;
		try {
			out = response.getWriter();
			out.print(json);
		} catch (Exception e) {
			log.error("error",e);
			
		}
	}

	/**
	 * 申领运单号
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "getExpress",method = RequestMethod.GET)
	public String getExpress(Model model) {
		ShiroUser user = getShiroUser();
		List<Customers> customers=null;
		try {
			customers=customersService.loadCustomerByAuthority(user);
			model.addAttribute("customers", customers);
			model.addAttribute("status", 0);
		} catch (Exception e) {
			
			log.error("申领运单号",e);
		}
		return "customers/customerBillNo";

	}
	
	@RequestMapping(value = "getExpress/{customerCode}",method = RequestMethod.GET)
	public String getExpressCustomerCode(@PathVariable(value="customerCode") String customerCode,Model model) {
		ShiroUser user = getShiroUser();
		List<Customers> customers=null;
		Customers customer=null;
		try {
			customers=customersService.loadCustomerByAuthority(user);
			customer=customersService.findByCustomerCode(customerCode);
			
			String express=TMSTransportRule.getExpress(customer.getStartNumber(),customer.getEndNumber());
			model.addAttribute("waybillNo", express);
			model.addAttribute("name", customer.getCustomerName());
			model.addAttribute("customerCode", customerCode);
			model.addAttribute("customers", customers);
			model.addAttribute("status", 1);
		} catch (Exception e) {
			
			log.error("申领运单号",e);
		}
		return "customers/customerBillNo";

	}


	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String createForm(Model model) {
		model.addAttribute("customers", new Customers());
		model.addAttribute("action", "create");
		return "customers/customersForm";
	}

	@RequestMapping(value = "create", method = RequestMethod.POST)
	public String create(@Valid Customers customers,
			RedirectAttributes redirectAttributes) {
		ShiroUser user=getShiroUser();
		try {
			Customers tempCustomers=customersService.findByCustomerCode(customers.getCustomerCode());
			if(tempCustomers==null){
				TMSTransportRule.getExpress(customers.getStartNumber(),customers.getEndNumber());
				customersService.save(customers,user.jobuuid);
				redirectAttributes.addFlashAttribute("message", "创建商家成功");
				
				try {
					//同步TMS商家信息
//					ObjectMapper object=new ObjectMapper();
//					String message=object.writeValueAsString(customers);
//					SynchroShippedBatchQueue.putSendMessageQueue("createCustomers"+StatusEnums.split.getStatus()+message);
//					
				} catch (Exception e) {
					
				}
			}else{
				redirectAttributes.addFlashAttribute("message", "该商家编码已经存在");
			}
			
			
		} catch (Exception e) {
			log.error("error",e);
			redirectAttributes.addFlashAttribute("message", e.getMessage());
		}
		return "redirect:/v2/customers/v2_show";
	}

	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	public String updateForm(@PathVariable("id") Long id, Model model) {
		Customers customer = customersService.findOne(id);
		model.addAttribute("customers", customer);
		model.addAttribute("action", "update");
		return "customers/customersForm";
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	public String update(
			@Valid @ModelAttribute("preloadCustomers") Customers customers,
			RedirectAttributes redirectAttributes) {
		try {
		    ShiroUser user = getShiroUser();
			Customers tempCustomers=customersService.findByCustomerCode(customers.getCustomerCode());
			if(tempCustomers!=null){
				if(tempCustomers.getId().intValue()!=customers.getId()){
					redirectAttributes.addFlashAttribute("message", "该商家编码已经存在");
					return "redirect:/v2/customers/v2_show";
				}
			}
			TMSTransportRule.getExpress(customers.getStartNumber(),customers.getEndNumber());
			customersService.save(customers);
			redirectAttributes.addFlashAttribute("message", "更新商家成功");
			try {
				//同步TMS商家信息
//				ObjectMapper object=new ObjectMapper();
//				String message=object.writeValueAsString(customers);
//				SynchroShippedBatchQueue.putSendMessageQueue("createCustomers"+StatusEnums.split.getStatus()+message);
				
			} catch (Exception e) {
				
			}
			log.info("UpdateCustomersResult--sectionPo({});placeStatus({});subStock({});passBack({});packStatus({});openQm({})--UpdateBy({},{})",
			    customers.getSectionPo(),customers.getPlaceStatus(),customers.getSubStock(),customers.getPassBack(),customers.getPackStatus(),customers.getPackStatus(),
			    user.realname,user.id);
		} catch (Exception e) {
			log.error("error",e);
			redirectAttributes.addFlashAttribute("message", e.getMessage());
		}
		return "redirect:/v2/customers/v2_show";
	}

	@RequestMapping(value = "delete/{id}")
	public String delete(@PathVariable("id") Long id,
			RedirectAttributes redirectAttributes) {
		try {
			customersService.delete(id);

			redirectAttributes.addFlashAttribute("message", "删除商家成功");
		} catch (Exception e) {
			log.error("error",e);
			redirectAttributes.addFlashAttribute("message", e.getMessage());
		}
		return "redirect:/v2/customers/v2_show";
	}

	/**
	 * 获取平台的详细信息
	 * 
	 * @param id
	 * @param response
	 */
	@RequestMapping(value = "ajaxCustomerInf")
	public void ajaxCustomerInf(@RequestParam(value = "id") long id,
			HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			Customers customers = customersService.findOne(id);
			if (customers == null) {
				json.put("status", "-1");
				json.put("content", "信息不存在");
				out.print(json.toString());
				return;
			}
			json.put("status", "1");
			json.put("content", customers);
			out.print(json.toString());
		} catch (Exception e) {
			log.error("error",e);
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
		}
	}
	
	/**
	 * 根据商家编码获取网点信息
	 * @param customerCode
	 * @param response
	 */
	@RequestMapping(value="ajaxAreaGroup")
	public void ajaxAreaGroup(@RequestParam(value="customerCode") String customerCode,HttpServletResponse response){
		JSONObject json=null;
		PrintWriter out=null;
		Customers customers=null;
		RestCustomersAreagroupVo restCustomersAreagroupVo = null;
		try {
			out=response.getWriter();
			json=new JSONObject();
			log.info("根据商家编码获取网点信息:"+customerCode);
			customers=customersService.findByCustomerCode(customerCode);
			if(null==customers){
				json.put("status", "-1");
				json.put("content", "该客户编码不存在");
				out.print(json.toString());
				return;
			}
			restCustomersAreagroupVo =customerAreaGroupService.getRestCustomersAreagroupVo(customerCode);//HttpPost.getRestCustomersAreagroupVo(customers);// 设置网点信息
			json.put("status", "1");
			json.put("content", restCustomersAreagroupVo);
			out.print(json.toString());
			log.info("根据商家编码获取网点信息:"+json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
		}
	}
	
	
	@RequestMapping(value = "ajaxfindShopSource")
	public void ajaxfindShopSource(@RequestParam(value = "ordenoSourceCode") String ordenoSourceCode,
			@RequestParam(value = "customerCode") String customerCode,
			HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		List<ShopSource> shopSources=null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			shopSources = shopSourceService.findByCustomerCodeAndOrdenoSourceCode(customerCode, ordenoSourceCode);
			
			json.put("status", "1");
			json.put("content", shopSources);
			out.print(json.toString());
		} catch (Exception e) {
			log.error("error",e);
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
		}
	}
	
	/**
	 * 根据客户编码返回平台信息
	 * @param customerCode
	 * @param response
	 */
	@RequestMapping(value = "ajaxfindOrdenoSource")
	public void ajaxfindOrdenoSource(@RequestParam(value = "customerCode") String customerCode,
			HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		ShiroUser user=getShiroUser();
		List<AreaGroup> areagroupList=null;
		List<OrdenoSource> ordenoSources=null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			ordenoSources = customersService.findOrdenoSource(customerCode);
			areagroupList=this.areaGroupService.loadAreaGroupByAuthority(user, customerCode);
			json.put("status", "1");
			json.put("content", ordenoSources);
			json.put("areaGroupCode", areagroupList);
			out.print(json.toString());
		} catch (Exception e) {
			log.error("error",e);
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
		}
	}

	/**
	 * 使用@ModelAttribute, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此本方法在该方法中执行.
	 */
	@ModelAttribute("preloadCustomers")
	public Customers getCustomers(
			@RequestParam(value = "id", required = false) Long id) {
		if (id != null) {
			return customersService.findOne(id);
		}
		return null;
	}
	
	/**
	 * 获取商家对应的仓库信息，跳转到分仓页面
	 *
	 * @param 
	 * @return 
	 * @throws 
	 * @author yuansheng
	 * @version 1.0.0
	 */
	@RequestMapping(value = "distributeWarehouse/{id}")
    public String distributeWarehouse(@PathVariable("id") Long id, String state , Model model){
	    warehouseAreaService.distributeWarehouse(id, state, model);
        return "customers/customerWarehouseOperate";
    }
	
	/**
	 * 修改商家是否分仓的状态
	 *
	 * @param 
	 * @return 
	 * @throws 
	 * @author yuansheng
	 * @version 1.0.0
	 */
	@ResponseBody
	@RequestMapping(value = "usingDistributeWarehouse")
	public Object usingDistributeWarehouse(String customerCode, String type){
	    try {
	        customersService.usingDistributeWarehouse(customerCode, type);
	        return "success";
        } catch (Exception e) {
            log.info("商家修改启用分仓状态", e);
            return "failure";
        }
	}
	
	@ResponseBody
    @RequestMapping(value = "updateStockQueryType")
    public Object updateStockQueryType(String customerCode, String type){
        try {
            customersService.updateStockQueryType(customerCode, type);
            return "success";
        } catch (Exception e) {
            log.info("商家修改库存查询类型", e);
            return "failure";
        }
    }
	
	/**
	 * 绑定仓库
	 *
	 * @param 
	 * @return 
	 * @throws 
	 * @author yuansheng
	 * @version 1.0.0
	 */
	@ResponseBody
	@RequestMapping(value = "bindWarehouse")
	public Object bindWarehouse(String customerCode, String warehouseCode){
	    try {
	        customersService.bindWarehouse(customerCode, warehouseCode);
	        return "success";
	    } catch (Exception e) {
	        log.info("商家修改主仓", e);
	        return "failure";
	    }
	}
	
    /**
     * 绑定主仓
     *
     * @param 
     * @return 
     * @throws 
     * @author yuansheng
     * @version 1.0.0
     */
    @ResponseBody
    @RequestMapping(value = "bindPrimaryWarehouse")
    public Object bindPrimaryWarehouse(String warehouseCode , String customerCode){
        try {
            customersService.bindPrimaryWarehouse(warehouseCode,customerCode);
            return "success";
        } catch (Exception e) {
            log.info("商家修改主仓异常", e);
            return "failure";
        }
    }
    
    // 跳转到覆盖区页面
    @RequestMapping(value = "toCoverageArea")
    public String toCoverageArea(String customerCode, String warehouseCode, Model model) {
        // 仓库信息
        AreaGroup warehouse = areaGroupService.findByGroupCode(warehouseCode);
        // 商家信息
        Customers customer = customersService.findByCustomerCode(customerCode);
        // 查找商家仓库覆盖区
        List<WarehouseArea> coverageAreas = warehouseAreaService.findCoverageArea(warehouseCode,customerCode);
        model.addAttribute("warehouse", warehouse);
        model.addAttribute("customer", customer);
        model.addAttribute("coverageAreas", coverageAreas);
        return "areagroup/areagroupOperate";
    }
	
    
    /**
     * 添加覆盖区
     *
     * @param 
     * @return 
     * @throws 
     * @author yuansheng
     * @version 1.0.0
     */
    @RequestMapping(value = "addCoverageArea")
    public String addCoverageArea(String customerCode, String warehouseCode, String SelectProvince , String SelectCity) {
        try {
            warehouseAreaService.addCoverageArea(customerCode, warehouseCode, SelectProvince, SelectCity);
        } catch (Exception e) {
            log.info("添加仓库覆盖区域异常", e);
        }
        return "redirect:/v2/customers/toCoverageArea?warehouseCode=" + warehouseCode + "&customerCode=" + customerCode;
    }
    
    
    /**
     * 删除覆盖区
     *
     * @param 
     * @return 
     * @throws 
     * @author yuansheng
     * @version 1.0.0
     */
    @ResponseBody
    @RequestMapping(value = "deleteCoverageArea")
    public String deleteCoverageArea(Long id) {
        try {
            warehouseAreaService.deleteCoverageArea(id);
            return "success";
        } catch (Exception e) {
            log.info("删除仓库覆盖区域异常", e);
            return "false";
        }
    }
    
    /**
     * 添加优先级
     *
     * @param 
     * @return 
     * @throws 
     * @author yuansheng
     * @version 1.0.0
     */
    @ResponseBody
    @RequestMapping(value = "addWarehouseLevel")
    public Object addWarehouseLevel(WarehouseAreaParamVo vo){
        try {
            customersService.addWarehouseLevel(vo);
            return "success";
        } catch (Exception e) {
            log.info("商家修改优先级失败", e);
            return "failure";
        }
    } 
}
